import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'

interface ProductDetailState {
  loading: boolean,
  error: null | unknown,
  data: any
}

// 初始化数据
const initialState: ProductDetailState = {
  loading: true,
  error: null,
  data: null
}

export const getProductDetail = createAsyncThunk(
  "productDetail/getProductDetail",
  async (touristRouteId: string | undefined, thunkAPI) => {
    //  thunkAPI.dispatch(productDetailSlice.actions.fetchStart())
    //  try {
       const { data: {data} } = await axios.get('https://mock.mengxuegu.com/mock/61c70e2ebba8817f8a413580/tourism_website/touristRoute')
       console.log("详情", data)
      //  thunkAPI.dispatch(productDetailSlice.actions.fetchSuccess(data))
    //  } catch (error) {
      //  let err = error
      //  thunkAPI.dispatch(productDetailSlice.actions.fetchFail(err))
    //  }

      return data
  }
)

export const productDetailSlice = createSlice({
  name: 'productDetail', // 命名空间名称
  initialState, // 初始化数据
  reducers: {
  
  }, // 这里的reducer是把action和reducer捆绑在了一起.所以不需要在单独定义action,这里的reducer是个对象
  extraReducers: {
    [getProductDetail.pending.type]: (state) => {
      // 原始写法
      // return { ...state, loading: true }
      state.loading = true  // immer
    },
    // reducer中已经提前定义好了action的参数
    // 请求成功
    [getProductDetail.fulfilled.type]: (state, action) => {
      state.loading = false
      state.data = action.payload
      state.error = null
    },
    // 请求失败
    [getProductDetail.rejected.type]: (state, action: PayloadAction<unknown | null>) => {
      state.loading = false
      state.error = action.payload
    }
  }
})